package com.testDemo.file;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: zouren
 * @date: 2022/4/14
 * @description:
 */

public class BatTest {
    /**
     * 执行bat脚本
     *
     * @param batScript 脚本内容
     * @param location  脚本存储路径
     * @return 结果
     */
    public static String executeBatScript(List<String> batScript, String location) {
        StringBuilder stringBuilder = new StringBuilder();
        File file = new File(location);
        Process process;

        try(FileOutputStream fos = new FileOutputStream(location);
            BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(fos, "GBK"))){
            //生成bat文件
            int len = batScript.size();
            String row = null;
            for (int i = 0; i < len; i++) {
                row = batScript.get(i);
                writer.write(row,0,row.length());
                writer.newLine();
            }
            writer.close();
            process = Runtime.getRuntime().exec(location);
            int exitValue = process.waitFor();
            System.out.println(String.format("exitValue=%s",exitValue ));

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(" \n");
            }
            process.destroy();
            System.out.println(String.format("stringBuilder=%s",stringBuilder));

            return stringBuilder.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        List<String> cmmand = new ArrayList<>();
        cmmand.add("cd D:/workspace/kettle/data-integration ");
        cmmand.add(String.format("Kitchen.bat /file:D:/workspace/kettle/workspace/ETLB/%s.kjb","我的"));
        executeBatScript(cmmand,"D:/workspace/kettle/workspace/startJob1.bat");
    }
}
